/*
Copyright © 2022 NAME HERE <huangxinbo@aliyun.com>

*/
package cmd

import (
	"fmt"
	"migrate/app"
	"migrate/app/db"

	"github.com/spf13/cobra"
)

// initCmd represents the init command
var initCmd = &cobra.Command{
	Use:   "init",
	Short: "initialize migration db",
	Run: func(cmd *cobra.Command, args []string) {
		filePath, _ := cmd.Flags().GetString("config")
		app.Setting(&Config, filePath)
		dbCtx := db.Db{
			Config: &Config,
		}
		err := dbCtx.NewDb()
		if err != nil {
			fmt.Printf("init db failed: %v\n", err)
			return
		}
		defer dbCtx.Close()
		dbCtx.Db.Exec("create database If not exists " + Config.DbName + " character set " + Config.Charset + " collate " + Config.Collate)
		dbCtx.Db.Exec("use " + Config.DbName)
		dbCtx.Db.AutoMigrate(&db.Migration{})
		fmt.Println("migrate init success")
	},
}

func init() {
	rootCmd.AddCommand(initCmd)

	initCmd.Flags().StringP("config", "c", ".migrate.yaml", "config file path")
}
